<template>
  <div class="prod_wrap">
    <el-card class="custom_card">
      <h1 class="h1">{{ pId ? `编辑${modelItemName}` : `新增${modelItemName}` }}</h1>
      <el-form ref="formRef" style="margin-top: 20px" label-width="120px" :rules="formRules" :model="form">
        <el-tabs type="border-card">
          <el-tab-pane label="基础信息">
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入标题" />
            </el-form-item>
            <el-form-item label="副标题">
              <el-input type="textarea" v-model="form.subtitle" placeholder="请输入副标题" />
            </el-form-item>
            <el-form-item label="分类" prop="categoryId">
              <el-cascader style="width: 400px" v-model="categoryArr" :options="caList" :props="props" clearable @change="handleChange" placeholder="请选择分类" />
            </el-form-item>
            <el-form-item label="跳转标识" prop="linkName">
              <el-input v-model="form.linkName" placeholder="请输入跳转标识(英文字母或者数字)" />
              <span style="font-size: 12px; color: #999999">跳转标识只能输入英文字母、数字</span>
            </el-form-item>
            <el-form-item label="是否发布">
              <el-radio-group v-model="form.isPublished" class="ml-4">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="是否推荐">
              <el-radio-group v-model="form.isRecommend" class="ml-4">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="是否置顶">
              <el-radio-group v-model="form.isTop" class="ml-4">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort" placeholder="请输入排序" />
            </el-form-item>
            <el-form-item label="主图">
              <ImageSelector type="img" v-model:imgUrl="form.mainImages"></ImageSelector>
            </el-form-item>
            <el-form-item label="子图">
              <ImageSelector type="imglist" v-model:imgList="form.thumbnailImages"></ImageSelector>
            </el-form-item>
            <el-form-item label="描述">
              <el-input type="textarea" class="w-full" v-model="form.description" show-word-limit :maxlength="400" :autosize="{ minRows: 4, maxRows: 10 }" placeholder="请输入描述" />
            </el-form-item>
            <el-form-item label="详情" prop="content">
              <Editor :value="form.content" @change="handleDetailChange" />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="标签">
            <el-button size="small" type="primary" @click="form.tags.push({ name: '' })">添加标签 </el-button>
            <el-form-item :key="idx" v-for="(item, idx) in form.tags" label="标签">
              <el-row type="flex">
                <el-col :md="12">
                  <el-input show-word-limit maxlength="5" v-model="item.name" />
                </el-col>
                <el-col :md="5" style="margin-left: 10px">
                  <el-button type="danger" size="small" @click="form.tags.splice(idx, 1)">删除 </el-button>
                </el-col>
              </el-row>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="技术参数">
            <el-button type="primary" size="small" @click="addtParams">
              <el-icon>
                <Plus />
              </el-icon>
              添加技术参数
            </el-button>
            <el-table :data="form.parameters">
              <el-table-column align="center" label="技术参数名称" prop="name"></el-table-column>
              <el-table-column align="center" label="技术参数值" prop="value">
                <template v-slot="{ row }">
                  <div v-html="row.value"></div>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作">
                <template v-slot="{ row, index }">
                  <el-button type="primary" text @click="editTParams(row, index)">编辑 </el-button>
                  <el-button type="danger" text @click="delTParams(row, index)">删除 </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="型号">
            <el-form-item label="型号">
              <el-input placeholder="请输入型号" v-model="form.modelType"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="SEO">
            <el-form-item label="SEO关键字">
              <el-input v-model="form.seoKey" placeholder="请输入SEO关键字" />
            </el-form-item>
            <el-form-item label="SEO描述">
              <el-input type="textarea" v-model="form.seoDesc" placeholder="请输入SEO描述" :autosize="{ minRows: 3, maxRows: 6 }" />
            </el-form-item>
            <el-form-item label="作者">
              <el-input v-model="form.author" placeholder="请输入作者" />
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
        <div class="flex-center">
          <el-button size="small" @click="router.back()">取消</el-button>
          <el-button size="small" @click="saveProduct" type="primary">保存 </el-button>
        </div>
      </el-form>
      <el-dialog :title="title" v-model="dialogVisible" @close="canceltParams">
        <el-form ref="addFormRef" label-width="120px">
          <el-form-item label="参数名称">
            <el-input v-model="addTParamsForm.name" placeholder="请输入参数名称" />
          </el-form-item>
          <el-form-item label="参数值">
            <el-input type="textarea" v-model="addTParamsForm.value" placeholder="请输入参数值"></el-input>
          </el-form-item>
          <el-form-item>
            <div class="op">
              <el-button size="small" @click="canceltParams">取消</el-button>
              <el-button size="small" type="primary" @click="confirmAddtParams">确定 </el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-dialog>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
// @ts-ignore
import Editor from "@/components/Editor/index.vue";
import { editProjectApi, addProjectApi, delProjectApi, getProjectById, getDetailByLinkName, getCategoryCount } from "@/api/content/project";
import { upload } from "../../api/usualManage";
import { getAllWebMenuByModelType } from "@/api/webmenus/index";
import { buildTreeData } from "@/utils/tools";
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from "element-plus";
import { useRoute, useRouter } from "vue-router";
// @ts-ignore
import ImageSelector from "@/components/ImageSelector/index.vue";

const editorRef = ref(null);
const formRef = ref<FormInstance>();
const pId = ref("");
const dialogVisible = ref(false);
const route = useRoute();
const modelItemName = decodeURIComponent(route.query.moduleName as string);
const modelItemId = route.query.moduleId;
const router = useRouter();
const caList = ref([]);
const rawCategoryData = ref<any[]>([]); // 保存原始平铺数据
const title = ref("");
const categoryArr = ref([]);

const addTParamsForm = ref({
  name: "",
  value: ""
});
const form = ref({
  title: "",
  subtitle: "",
  mainImages: "",
  thumbnailImages: [],
  description: "",
  content: "",
  tags: [],
  modelType: "",
  parameters: [],
  categoryId: "",
  categoryName: "",
  isPublished: true,
  isRecommend: false,
  modelId: modelItemId,
  modelName: modelItemName,
  seoKey: "",
  seoDesc: "",
  author: "",
  linkName: "",
  link: "",
  isTop: false,
  sort: -1
});

// 表单验证规则
const formRules: FormRules = {
  title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
  linkName: [{ required: true, message: "跳转链接不能为空", trigger: "blur" }],
  content: [{ required: true, message: "详情内容不能为空", trigger: "blur" }],
  categoryId: [{ required: true, message: "分类不能为空", trigger: "change" }]
};

const addtParams = () => {
  isEdit.value = false;
  dialogVisible.value = true;
};
const canceltParams = () => {
  dialogVisible.value = false;
  addTParamsForm.value.name = "";
  addTParamsForm.value.value = "";
};
const isEdit = ref(false);
const editIdx = ref<number>();
const editTParams = (row: any, index: number) => {
  isEdit.value = true;
  const idx = form.value.parameters.findIndex((item) => item.name === row.name);
  if (idx !== -1) {
    editIdx.value = idx;
  }
  dialogVisible.value = true;
  const clone = JSON.parse(JSON.stringify(row));
  addTParamsForm.value.name = clone.name;
  addTParamsForm.value.value = clone.value;
};
const delTParams = (row: any, idx: number) => {
  const index = form.value.parameters.findIndex((item) => item.name === row.name);
  if (index !== -1) {
    form.value.parameters.splice(index, 1);
  }
  // form.value.parameters.splice(idx, 1);
};
const confirmAddtParams = () => {
  const clone = JSON.parse(JSON.stringify(addTParamsForm.value));
  if (isEdit.value) {
    form.value.parameters.splice(editIdx.value, 1, clone);
  } else {
    form.value.parameters.push(clone);
  }
  dialogVisible.value = false;
  addTParamsForm.value.name = "";
  addTParamsForm.value.value = "";
};
const props = {
  expandTrigger: "hover" as const,
  value: "code",
  label: "name",
  children: "children",
  checkStrictly: true
};

/**
 * 根据分类code查找分类名称
 * @param code 分类编码
 * @param data 原始分类数据
 * @returns 分类名称
 */
const findCategoryNameByCode = (code: string, data: any[]): any => {
  const category = data.find((item) => item.code === code);
  return category ? category : null;
};

/**
 * 处理级联选择器变化事件
 * 根据选中的值设置分类ID和分类名称
 * @param value 级联选择器返回的值数组
 */
const handleChange = (value) => {
  if (Array.isArray(value) && value.length > 0) {
    // 取最后一个值作为分类ID（最深层级的分类）
    const selectedCategoryId = value[value.length - 1];
    form.value.categoryId = selectedCategoryId;

    // 根据分类ID查找分类名称并赋值
    if (rawCategoryData.value.length > 0) {
      const category = findCategoryNameByCode(selectedCategoryId, rawCategoryData.value);
      form.value.categoryName = category ? category.name : "";
    }
    getCategoryCount({
      title: "",
      moduleId: "",
      categoryId: selectedCategoryId
    }).then((res) => {
      if (res.status === 200) {
        form.value.linkName = res.data.total + 1;
      }
    });
  } else {
    form.value.categoryId = "";
    form.value.categoryName = "";
  }
};

/**
 * 根据分类ID查找完整的路径
 * @param categoryId 分类ID
 * @param data 原始平铺数据
 * @returns 从根节点到目标节点的路径数组
 */
const findCategoryPath = (categoryId: string, data: any[]): string[] => {
  const path: string[] = [];

  // 根据categoryId查找对应的分类项
  const findPath = (id: string): boolean => {
    const category = data.find((item) => item.code === id);
    if (!category) return false;

    path.unshift(category.code);

    if (category.parentCode) {
      return findPath(category.parentCode);
    }
    return true;
  };

  findPath(categoryId);
  return path;
};

/**
 * 根据分类ID设置级联选择器的值
 * @param categoryId 分类ID
 */
const setCascaderValueByCategoryId = (categoryId: string) => {
  if (!categoryId) {
    categoryArr.value = [];
    return;
  }

  // 使用已保存的原始数据查找路径
  if (rawCategoryData.value.length > 0) {
    const path = findCategoryPath(categoryId, rawCategoryData.value);
    categoryArr.value = path;

    // 同时设置分类名称
    const category = findCategoryNameByCode(categoryId, rawCategoryData.value);
    form.value.categoryName = category ? category.name : "";
  } else {
    // 如果原始数据还没加载，降级处理
    categoryArr.value = [categoryId];
  }
};

/**
 * 加载分类列表数据
 * 获取分类数据并构建树形结构
 */
const loadCateList = async () => {
  try {
    const res = await getAllWebMenuByModelType("category", 1);
    const rawData = (res.data || res) as any[];
    // 保存原始平铺数据
    rawCategoryData.value = rawData;
    // 将平铺数据转换为树形结构
    caList.value = buildTreeData(rawData);
  } catch (error) {
    console.error("获取分类列表失败:", error);
    ElMessage.error("获取分类列表失败");
  }
  // getAllWebMenuByModelType("category", 1)
  //   .then((res) => {
  //     const rawData = (res.data || res) as any[];
  //     // 保存原始平铺数据
  //     rawCategoryData.value = rawData;
  //     // 将平铺数据转换为树形结构
  //     caList.value = buildTreeData(rawData);
  //   })
  //   .catch((error) => {
  //     console.error("获取分类列表失败:", error);
  //     ElMessage.error("获取分类列表失败");
  //   });
};

/**
 * 保存产品信息
 * 根据是否有产品ID判断是新增还是编辑
 */
const saveProduct = async () => {
  if (!formRef.value) return;

  try {
    // 验证表单
    await formRef.value.validate();
    // 检查linkName是否已存在
    if (pId.value) {
      const category = findCategoryNameByCode(form.value.categoryId, rawCategoryData.value);
      form.value.link = category ? category.link + "/" + form.value.linkName : "";
      await editProjectApi(pId.value, form.value);
      ElMessage({
        type: "success",
        message: "修改成功"
      });
      router.back();
    } else {
      console.log("12");

      const existingProduct = await getDetailByLinkName(form.value.linkName);
      if (existingProduct && existingProduct.data) {
        ElMessage.error("linkName已存在，请输入其他名称");
        return false;
      }
      const category = findCategoryNameByCode(form.value.categoryId, rawCategoryData.value);
      console.log(category, "category");
      form.value.link = category ? category.link + "/" + form.value.linkName : "";
      await addProjectApi(form.value);
      ElMessage({
        type: "success",
        message: "添加成功"
      });
      router.back();
    }
  } catch (error) {
    console.error("表单验证失败或保存失败:", error);
    if (error !== false) {
      // 如果不是表单验证失败
      ElMessage.error("保存失败，请重试");
    }
  }
};
const handleDetailChange = (value: string) => {
  form.value.content = value;
};
const handleChangeTParams = (value: string) => {
  addTParamsForm.value.value = value;
};
// 初始化页面数据
const initPage = async () => {
  // 获取路由参数中的产品ID
  pId.value = route.query.pId as string;

  // 加载分类列表
  await loadCateList();

  // 如果有产品ID，则获取产品详情进行编辑
  if (pId.value) {
    getProjectById(pId.value)
      .then((res) => {
        const data = res.data || res;
        Object.assign(form.value, {
          title: data.title || "",
          subtitle: data.subtitle || "",
          mainImages: data.mainImages || "",
          thumbnailImages: data.thumbnailImages || [],
          description: data.description || "",
          content: data.content || "",
          tags: data.tags || [],
          modelType: data.modelType || "",
          parameters: data.parameters || [],
          categoryId: data.categoryId || "",
          categoryName: data.categoryName || "",
          isPublished: data.isPublished || false,
          isRecommend: data.isRecommend || false,
          seoKey: data.seoKey || "",
          seoDesc: data.seoDesc || "",
          author: data.author || "",
          linkName: data.linkName || "",
          link: data.link || "",
          sort: data.sort || -1,
          isTop: data.isTop || false
        });

        // 设置分类级联选择器的值
        if (data.categoryId) {
          setCascaderValueByCategoryId(data.categoryId);
        }
      })
      .catch((error) => {
        console.error("获取产品详情失败:", error);
        ElMessage.error("获取产品详情失败");
      });
  }
};
initPage();
</script>
<style lang="less" scoped>
.prod_wrap {
  width: 80%;
  margin: 0 auto;
}

.custom_card {
  min-height: 1200px;
}

.flex-center {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  width: 100%;
}

.h1 {
  font-size: 18px;
  font-weight: bold;
  text-align: center;
}

.op {
  display: flex;
  justify-content: flex-end;
}

.tag-col {
  display: flex;
}

.w-400 {
  width: 400px;
}
</style>
